<template>
  <el-watermark :content="['风伯']">
    <div class="material-manager">
      <el-card>
        <el-form :model="searchForm" inline="true" class="search-form" label-width="70px">
          <el-form-item label="物料编号">
            <el-input v-model.trim="searchForm.materialCode" placeholder="请输入物料编号" class="wi-240px" clearable />
          </el-form-item>
          <el-form-item label="物料名称">
            <el-input v-model.trim="searchForm.materialName" placeholder="请输入物料名称" class="wi-240px" clearable />
          </el-form-item>
          <el-form-item label="物料类型">
            <el-select v-model="searchForm.materialType" placeholder="请选择物料类型" class="wi-240px" clearable>
              <el-option label="测试重复" value="测试重复" />
              <el-option label="汽车" value="汽车" />
              <el-option label="原材料" value="原材料" />
            </el-select>
          </el-form-item>
          <el-form-item label="物料状态">
            <el-select v-model="searchForm.materialStatus" placeholder="请选择物料状态" class="wi-240px" clearable>
              <el-option label="启用" value="0" />
              <el-option label="禁用" value="1" />
            </el-select>
          </el-form-item>
        </el-form>
        <el-form-item style="float: right">
          <el-button type="success" @click="searchMaterials">查询</el-button>
          <el-button @click="reLoad">重置</el-button>
        </el-form-item>
      </el-card>

      <el-card style="margin-top: 20px">
        <el-form-item style="float: right; margin: 20px">
          <el-button type="success" @click="creatematerial">新增</el-button>

          <el-button @click="resetSearch">导入</el-button>
        </el-form-item>
        <!--物料表格-->
        <el-table :data="materialData" style="width: 100%" height="400">
          <el-table-column type="selection" width="55" fixed />
          <el-table-column prop="index" label="序号" width="50" type="index" fixed />
          <el-table-column prop="materialCode" label="物料编号" fixed />
          <el-table-column prop="materialName" label="物料名称" fixed />
          <el-table-column prop="materialStatus" label="物料状态">
            <template #default="scope">
              <div v-if="scope.row.materialStatus === '0'">
                <el-icon>
                  <svg
                    t="1728888035706"
                    class="icon"
                    viewBox="0 0 1024 1024"
                    version="1.1"
                    xmlns="http://www.w3.org/2000/svg"
                    p-id="4296"
                  >
                    <path d="M512 624a112 112 0 1 0 0-224 112 112 0 0 0 0 224z" p-id="4297" fill="#1afa29" />
                  </svg>
                </el-icon>
                <span style="font-size: 14px; vertical-align: middle">启用</span>
              </div>
              <div v-else>
                <svg
                  t="1728897635439"
                  class="icon"
                  viewBox="0 0 1024 1024"
                  version="1.1"
                  xmlns="http://www.w3.org/2000/svg"
                  p-id="3550"
                  width="15"
                  height="15"
                >
                  <path d="M512 624a112 112 0 1 0 0-224 112 112 0 0 0 0 224z" p-id="3551" fill="#d81e06" />
                </svg>
                <span style="font-size: 14px; vertical-align: middle">禁用</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="materialType" label="物料类型" />
          <el-table-column prop="materialTypeCode" label="物料类型编号" />
          <el-table-column prop="specification" label="规格" />
          <el-table-column prop="basicUnit" label="基本计量单位" />
          <el-table-column label="操作" fixed="right">
            <template #default="scope">
              <el-button link type="success" size="small" @click="editput(scope.row.id)">编辑</el-button>
              <el-button link type="danger" size="small" @click="deleteRow(scope.row.id)">删除</el-button>
              <el-button
                v-if="scope.row.materialStatus == '1'"
                link
                type="success"
                size="small"
                @click="disableRow(scope.row.id)"
              >
                启用
              </el-button>
              <el-button v-else link type="danger" size="small" @click="disableRow(scope.row.id)">禁用</el-button>
              <el-dropdown trigger="hover" @command="handleCommand">
                <el-button type="default" link style="font-weight: 700">...</el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="viewDrawing">查看图纸</el-dropdown-item>

                    <el-dropdown-item command="viewPackage">查看包装规格</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <!--分页-->
        <div style="display: flex; justify-content: space-between; flex: 1">
          <div style="flex: 1" />
          <el-pagination
            style="padding: 10px"
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20, 30, 40]"
            :size="size"
            :total="totals"
            background
            type="success"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
      <!--导入-->
      <el-dialog v-model="dialogVisible" title="物料导入" width="800" :before-close="handleClose">
        <el-upload
          ref="uploadRef"
          class="upload-demo"
          drag
          action="http://192.168.100.138:9097/admin/materials/uploadExcel"
          multiple
          accept=".xls,.xlsx"
          :auto-upload="false"
        >
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>

          <template #tip>
            <div style="text-align: center">
              仅允许导入xls、xlsx格式文件。
              <el-button :key="'primary'" :type="'primary'" link @click="downloadTemplate">下载模板</el-button>
            </div>
            <el-form-item style="margin-left: 75%">
              <el-button type="success" @click="update">确认</el-button>
              <el-button @click="cancel">取消</el-button>
            </el-form-item>
          </template>
        </el-upload>
      </el-dialog>
      <!--新增，编辑物料弹窗-->
      <el-dialog
        v-model="pop"
        :title="isEditing ? '修改物料信息' : '添加物料信息'"
        width="800"
        :before-close="handleClose"
      >
        <el-form
          ref="materialRef"
          :model="materialForm"
          label-width="100px"
          inline="true"
          style="display: grid; grid-template-columns: repeat(3, 1fr)"
        >
          <el-form-item
            label="物料编号"
            :rules="[{ required: true, message: '物料编号不能为空', trigger: 'blur' }]"
            laidth="80px"
            prop="matnr"
          >
            <el-input
              v-model="materialForm.matnr"
              placeholder=""
              class="wi-240px"
              minlength="0"
              maxlength="64"
              show-word-limit
            />
          </el-form-item>

          <el-form-item
            label="物料名称"
            :rules="[{ required: true, message: '物料名称不能为空', trigger: 'blur' }]"
            label-width="100px"
            prop="maktxZh"
          >
            <el-input
              v-model="materialForm.maktxZh"
              placeholder=""
              class="wi-240px"
              minlength="0"
              maxlength="64"
              show-word-limit
            />
          </el-form-item>

          <el-form-item
            label="供方料号"
            label-width="100px"
            prop="idnlf"
            :rules="[{ max: 64, message: '只能写到64', trigger: 'blur' }]"
          >
            <el-input
              v-model="materialForm.idnlf"
              placeholder="请输入供方料号"
              clearable
              class="wi-240px"
              minlength="0"
              maxlength="64"
              show-word-limit
            />
          </el-form-item>

          <el-form-item
            label="物料类型"
            :rules="{ required: true, message: '物料类型不能为空', trigger: 'change' }"
            label-width="100px"
            prop="mtart"
          >
            <el-select v-model="materialForm.mtart" placeholder="请选择材料类型" clearable class="wi-240px">
              <el-option label="原材料" value="原材料" />
            </el-select>
          </el-form-item>

          <el-form-item label="物料组" prop="matkl">
            <el-select v-model="materialForm.matkl" placeholder="请选择物料组" clearable class="wi-240px">
              <el-option label="一组" value="one" />

              <el-option label="二组" value="two" />

              <el-option label="三组" value="three" />
            </el-select>
          </el-form-item>

          <el-form-item label="产品组" prop="spart">
            <el-select v-model="materialForm.spart" placeholder="请选择产品组" clearable class="wi-240px">
              <el-option label="一组" value="one" />

              <el-option label="二组" value="two" />

              <el-option label="三组" value="three" />
            </el-select>
          </el-form-item>

          <el-form-item
            label="规格"
            prop="groes"
            :rules="[{ required: true, message: '规格不能为空', trigger: 'blur' }]"
          >
            <el-input
              v-model="materialForm.groes"
              placeholder="请输入规格"
              clearable
              class="wi-240px"
              minlength="0"
              maxlength="64"
              show-word-limit
            />
          </el-form-item>

          <el-form-item
            label="基本单位"
            prop="meins"
            :rules="[{ required: true, message: '基本单位不能为空', trigger: 'change' }]"
          >
            <el-select v-model="materialForm.meins" placeholder="请选择基本单位" clearable class="wi-240px">
              <el-option label="根" value="根" />

              <el-option label="个" value="个" />

              <el-option label="毫升" value="毫升" />

              <el-option label="米" value="米" />
            </el-select>
          </el-form-item>

          <el-form-item
            label="物料状态"
            prop="materialstate"
            :rules="[{ required: true, message: '物料状态不能为空', trigger: 'change' }]"
          >
            <el-select v-model="materialForm.materialstate" placeholder="请选择物料状态" class="wi-240px">
              <el-option label="启用" value="0" />

              <el-option label="禁用" value="1" />
            </el-select>
          </el-form-item>

          <el-form-item label="重量单位" prop="gewei">
            <el-select v-model="materialForm.gewei" placeholder="请选择重量单位" class="wi-240px">
              <el-option label="kg" value="kg" />
            </el-select>
          </el-form-item>

          <el-form-item label="长度单位" prop="lengthUnit">
            <el-select v-model="materialForm.lengthUnit" placeholder="请选择长度单位" clearable class="wi-240px">
              <el-option label="cm" value="cm" />
            </el-select>
          </el-form-item>

          <el-form-item label="宽度" prop="breit" :rules="[{ max: 5, message: '只能写到30', trigger: 'blur' }]">
            <el-input
              v-model="materialForm.breit"
              placeholder="请输入宽度"
              clearable
              class="wi-240px"
              minlength="0"
              maxlength="30"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="数量" prop="wesch" :rules="[{ max: 30, message: '只能写到30', trigger: 'blur' }]">
            <el-input
              v-model="materialForm.wesch"
              placeholder="请输入数量"
              clearable
              class="wi-240px"
              minlength="0"
              maxlength="30"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="毛重" prop="brgew" :rules="[{ max: 30, message: '只能写到30', trigger: 'blur' }]">
            <el-input
              v-model="materialForm.brgew"
              placeholder="请输入毛重"
              clearable
              class="wi-240px"
              minlength="0"
              maxlength="30"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="净里" prop="ntgew" :rules="[{ max: 30, message: '只能写到30', trigger: 'blur' }]">
            <el-input
              v-model="materialForm.ntgew"
              placeholder="请输入净里"
              clearable
              class="wi-240px"
              minlength="0"
              maxlength="30"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="长度" prop="laeng" :rules="[{ max: 30, message: '只能写到30', trigger: 'blur' }]">
            <el-input
              v-model="materialForm.laeng"
              placeholder="请输入长度"
              clearable
              class="wi-240px"
              minlength="0"
              maxlength="30"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="高度" prop="hoehe" :rules="[{ max: 30, message: '只能写到30', trigger: 'blur' }]">
            <el-input
              v-model="materialForm.hoehe"
              placeholder="请输入高度"
              clearable
              class="wi-240px"
              minlength="0"
              maxlength="30"
              show-word-limit
            />
          </el-form-item>
        </el-form>
        <el-card>
          <el-col :span="1.5" style="padding-bottom: 20px">
            <h3 style="font-weight: 1000">物料的工厂数据</h3>

            <el-button type="success" style="margin-top: 20px" @click="handleAdd">添加一行</el-button>
          </el-col>

          <el-table :data="data.arr" style="color: dimgray" border>
            <el-table-column prop="id" label="行项目" width="60px" />

            <el-table-column prop="name" label="工厂" width="100px" />

            <el-table-column prop="tean" label="采购组" width="150px" />

            <el-table-column prop="day" label="计划交货天数" width="150px" />

            <el-table-column prop="num" label="安全库存" width="150px" />

            <el-table-column prop="maney" label="利润中心" width="150px" />

            <el-table-column prop="operate" label="操作" width="200px">
              <template #default="{}">
                <el-button type="success" link size="small">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-form-item style="margin-top: 20px; margin-left: 70%">
            <template #default="{}">
              <el-button v-if="isEditing == false" type="success" @click="addData">新增</el-button>
              <el-button v-else type="success" @click="edit">保存</el-button>

              <el-button @click="cancel">取消</el-button>
            </template>
          </el-form-item>
        </el-card>
      </el-dialog>
    </div>
  </el-watermark>
</template>
  
<script setup lang='ts'>
import { onMounted, reactive, ref } from 'vue'
import axios from 'axios'

//组件引入
const searchForm = reactive({
  materialName: '',
  materialStatus: '',
  materialCode: '',
  materialType: ''
})
const materialForm = reactive<any>({
  id: '',
  matnr: '',
  maktxZh: '',
  idnlf: '',
  mtart: '',
  matkl: '',
  spart: '',
  groes: '',
  meins: '',
  materialstate: '',
  gewei: '',
  lengthUnit: '',
  breit: '',
  wesch: '',
  brgew: '',
  ntgew: '',
  laeng: '',
  hoehe: ''
})

const materialData = ref([])
const data = ref({
  arr: [{ id: '1', name: '友达公司', tean: '第二组', day: '15', num: '', maney: '', operate: '删除' }]
})

//分页
const currentPage = ref(1)
const pageSize = ref(10)
const size = ref(10)
const totals = ref(0)
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchData()
}
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchData()
}

//载入数据
const fetchData = async () => {
  try {
    const response = await axios({
      method: 'post',
      url: 'http://192.168.100.138:9097/admin/materials/querybypage',
      params: {
        currentPage: currentPage.value,
        pageSize: pageSize.value
      }
    })
    const result = response.data

    materialData.value = result.records.map((item) => {
      return {
        id: item.id.toString(),
        materialCode: item.matnr,
        materialName: item.maktxZh,
        materialStatus: item.materialState,
        materialType: item.mtart,
        materialTypeCode: item.mtartId,
        specification: item.groes,
        basicUnit: item.meins
      }
    })
    totals.value = result.total
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}
onMounted(() => {
  fetchData()
})
//查询
const searchMaterials = async () => {
  try {
    const response = await axios({
      method: 'post',
      url: 'http://192.168.100.138:9097/admin/materials/querybypage',
      params: {
        currentPage: currentPage.value,
        pageSize: pageSize.value,
        matnr: searchForm.materialCode,
        maktxZh: searchForm.materialName,
        mtart: searchForm.materialType,
        materialState: searchForm.materialStatus
      }
    })
    const result = response.data
    materialData.value = result.records.map((item) => {
      return {
        id: item.id,
        materialCode: item.matnr,
        materialName: item.maktxZh,
        materialStatus: item.materialState,
        materialType: item.mtart,
        materialTypeCode: item.mtartId,
        specification: item.groes,
        basicUnit: item.meins
      }
    })
    totals.value = result.total
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}

//导入弹窗
import { ElMessage, ElMessageBox, ElNotification, type UploadInstance } from 'element-plus'
const dialogVisible = ref(false)
const resetSearch = () => {
  dialogVisible.value = true
}
const uploadRef = ref<UploadInstance | null>(null)
const update = () => {
  uploadRef.value!.submit()
}
//下载模板
const downloadTemplate = async () => {
  try {
    const data: any = 'http://192.168.100.138:9097/admin/materials/downloadTemplate '
    location.href = data
  } catch (error) {
    console.error('下载模板失败：', error)
  }
}

//新增
const materialRef = ref()
const isEditing = ref()
const pop = ref(false)
const creatematerial = () => {
  pop.value = true
  resetFields()
  isEditing.value = false
}
//新增确认
const addData = async () => {
  await materialRef.value.validate((valid) => {
    if (valid) {
      console.log('表单校验成功')
      ElMessage.success('表单提交成功')
      try {
        axios.post('http://192.168.100.138:9097/admin/materials/addMaterial', materialForm)
      } catch (error) {
        console.error('新增数据失败:', error)
      }
    } else {
      console.log('表单校验失败')

      ElMessage.error('表单校验失败')
    }
  })
}
//删除
const deleteRow = async (id) => {
  try {
    const response = await axios.delete(`http://192.168.100.138:9097/admin/materials/${id}`)
    if (response.data.code === 0) {
      ElNotification({
        title: 'Success',
        message: '删除成功',
        type: 'success'
      })
      fetchData()
    }
  } catch (error) {
    console.error('删除数据失败:', error)
  }
}
//查看编辑
const editput = async (id) => {
  isEditing.value = true
  pop.value = true
  try {
    const response = await axios.get(`http://192.168.100.138:9097/admin/materials/${id}`)
    const result = response.data
    Object.assign(materialForm, result)
  } catch (error) {
    console.error('查看编辑数据失败:', error)
  }
}
//禁用启用
const disableRow = async (id) => {
  try {
    await axios.post(`http://192.168.100.138:9097/admin/materials/toggleStatus/${id}`)
    fetchData()
  } catch (error) {
    console.error('状态转变失败:', error)
  }
}

//提交编辑
const edit = async () => {
  try {
    await materialForm.value.validata((valid) => {
      if (valid) {
        console.log('表单校验成功')

        ElMessage.success('表单提交成功')
      } else {
        console.log('表单校验失败')

        ElMessage.error('表单校验失败')
      }
    })
    axios.put(`http://192.168.100.138:9097/admin/materials/updateMaterialById/${materialForm.id}`, {
      id: materialForm.id,
      matnr: materialForm.matnr,
      maktxZh: materialForm.maktxZh,
      idnlf: materialForm.idnlf,
      mtart: materialForm.mtart,
      matkl: materialForm.matkl,
      spart: materialForm.spart,
      groes: materialForm.groes,
      meins: materialForm.meins,
      materialState: materialForm.materialState,
      gewei: materialForm.gewei,
      lengthUnit: materialForm.lengthUnit,
      breit: materialForm.breit,
      wesch: materialForm.wesch,
      brgew: materialForm.brgew,
      ntgew: materialForm.ntgew,
      laeng: materialForm.laeng,
      hoehe: materialForm.hoehe
    })
  } catch (error) {
    console.error('编辑提交失败:', error)
  }
  resetFields()
  pop.value = false
  fetchData()
}

function handleCommand(command: string) {
  switch (command) {
    case 'viewDrawing':
      break
    case 'viewPackage':
      break
    default:
  }
}
const handleAdd = () => {}
//全局配置
//关闭窗口
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('确定要关闭这个弹窗吗?')
    .then(() => {
      resetFields()
      done()
    })
    .catch(() => {
      // catch error
    })
}
//取消
const cancel = () => {
  pop.value = false
  dialogVisible.value = false
  resetFields()
  materialRef.value.clearValidate()
  console.log(materialRef.value)

  uploadRef.value!.clearFiles()
}
//重置
const reLoad = () => {
  Object.assign(searchForm, {
    materialCode: '',
    materialName: '',
    materialType: '',
    materialStatus: ''
  })
}

//清空
const resetFields = () => {
  Object.assign(materialForm, {
    matnr: '',
    maktxZh: '',
    idnlf: '',
    mtart: '',
    matkl: '',
    spart: '',
    groes: '',
    meins: '',
    materialstate: '',
    gewei: '',
    lengthUnit: '',
    breit: '',
    wesch: '',
    brgew: '',
    ntgew: '',
    laeng: '',
    hoehe: ''
  })
}
</script>
  
<style>
.background-color {
  background-color: gainsboro;
}
.material-manager {
  background-color: white;
  width: 100%;
  margin: auto;
}
.el-pagination.is-background .el-pager li:not(.disabled) {
  background-color: #fff;
  color: #666;
}

.el-pagination.is-background .el-pager li:not(.disabled):hover {
  background-color: #e6e6e6;
}

.el-pagination.is-background .el-pager li:not(.disabled).is-active {
  background-color: #67c23a;
  color: #fff;
}
</style>